package com.yiyiooo.Abp.basics;

import com.google.gson.reflect.TypeToken;
import com.yiyiooo.client.invoker.ApiCallback;
import com.yiyiooo.client.invoker.ApiException;
import com.yiyiooo.client.invoker.JSON;

import java.lang.reflect.Type;
import java.util.Map;

public abstract class AbpApiCallback<T> implements ApiCallback {
    final HttpClientResult<T> result = new HttpClientResult<T>();
    @Override
    public void onFailure(ApiException e, int statusCode, Map responseHeaders) {
        if (e != null && e.getResponseBody()!=null && !e.getResponseBody().equals("")) {
            try {
                Type ReturnType = new TypeToken<AbpResultDto<T>>(){}.getType();
                AbpResultDto<T> jsonData = new JSON().deserialize(e.getResponseBody(),ReturnType); //.deserialize<AbpResultDto<T>>(e?.responseBody, ReturnType)
                result.errMessage = jsonData.error.message;
            }catch (Exception ex){
                result.errMessage ="Bad Request; statusCode:"+statusCode;
            }
        }else{
            result.errMessage = "Bad Request; statusCode:"+statusCode;
        }
        result.error = true;
        call(result);
    }

    @Override
    public void onSuccess(Object successResult, int statusCode, Map responseHeaders) {
        result.success = true;
        result.result = (T)successResult;
        call(result);
    }

    @Override
    public void onUploadProgress(long bytesWritten, long contentLength, boolean done) {

    }

    @Override
    public void onDownloadProgress(long bytesRead, long contentLength, boolean done) {

    }
    public abstract  void call(HttpClientResult<T> callData);
}
